//
//  MTCertificationController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/7.
//  Copyright © 2020 张强. All rights reserved.
//

/// 键盘
import IQKeyboardManagerSwift

/// 网络

import Moya
import Result
import RxSwift
import RxCocoa
import MTCategory
import YPNavigationBarTransition

class MTCertificationController: BaseViewController{
    
    /// MTProvider
    private lazy var provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    lazy var tableView: CertificationTableView = {
        let tv = CertificationTableView(frame: self.view.bounds)
        tv.verificationTask = self
        return tv
    }()
    
    var completionHandler: (()->())?
    
    //身份证正面/反面
    private var isFront: Bool = true
    
    ///正面照URL
    private var frontUrl: String?
    
    ///反面照URL
    private var backUrl: String?
    
    lazy var checkoutButton: UIView = {
        let btn = UIButton()
        btn.setTitle("提交认证", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(certificationController(didClickCommitButton:)), for: .touchUpInside)
        return btn
    }()
    
    deinit {
        removeNotifications()
    }
    
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTCertificationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        addNotifications()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTCertificationController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "实名认证"
        view.addSubview(tableView)
//        view.addSubview(checkoutButton)
//        checkoutButton.snp.makeConstraints { (make) in
//            make.left.equalTo(view).offset(20)
//            make.right.equalTo(view).offset(-20)
//            make.height.equalTo(50)
//            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
//        }
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTCertificationController {
    
    private func certificationController(didClickCommitButton sender: UIButton) {
        
    }
    
    private func shouldPresentPhotoLibraryFront() {
        isFront = true
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.allowVideoSelection = false
        c.maxSelectdCount = 1
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    private func shouldPresentPhotoLibraryBack() {
        isFront = false
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.allowVideoSelection = false
        c.maxSelectdCount = 1
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
}

// MARK: ------------------ 通知相关 ----------------------
extension MTCertificationController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(shouldPresentPhotoLibraryFront), name: GlobalNotificationName.idFront.name, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(shouldPresentPhotoLibraryBack), name: GlobalNotificationName.idBack.name, object: nil)
    }

    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension MTCertificationController {
    private func uploadImage(image: UIImage, isFront: Bool) {
        /// 添加 indicator
        _ = self.provider.originRequest(.upload(image), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in

            /// 取消 indicator
            guard let weakSelf = self else { return }
            switch result {
            case let .success(response):
                guard let dict = try? response.mapJSON() as? [String:Any], let code = dict["code"] as? Int else { return }
                if code == 200, let imageUrl = dict["result"] as? String  {
                    if isFront {
                        weakSelf.frontUrl = imageUrl
                    } else {
                        weakSelf.backUrl = imageUrl
                    }
                } else {
                    DispatchQueue.main.async {
                        AlertManager.presentAlertView(message: "上传头像失败")
                    }
                }
                break

            case let .failure(error):
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: error.localizedDescription)
                }
                break

            }
        }
    }
}

// MARK: ------------------ PhotoLibraryViewControllerDelegate ----------------------
extension MTCertificationController: PhotoLibraryViewControllerDelegate {
    
    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
        MTAssetLibrary.default.requestImage(withAsset: asset.asset) { [weak self] (image, info, isDegraded) in
            guard let weakself = self else { return }
            guard let image = image else { return }
            if isDegraded == false {
                weakself.uploadImage(image: image, isFront: weakself.isFront)
            }
            if weakself.isFront {
                weakself.tableView.idImgFront = asset
            } else {
                weakself.tableView.idImgBack = asset
            }
//            if isDegraded == false, let image = image {
//                if let m = m {
//                    progressGroup[i] = weakself.calculateProgress(group: progressGroup, percentage: 0.01, doneProgress: 0)
//                    weakself.uploadTableView.update(model: m)
//                }
//                images[i] = image
//                group.leave()
//            }
        }
//        tableView.imageAsset = asset
    }
    
}


// MARK: ------------------ 初始认证代理回调 CertificationTableViewTask ----------------------
extension MTCertificationController: CertificationTableViewTask {
    
    func certificationTableView(_ tableView: CertificationTableView, willSubmitInfosWithRealName realname: String, idNumber: String) {
        let params: [String: String] = ["idImgUrlBackend"     : self.backUrl ?? "",
                                        "idImgUrlFront"       : self.frontUrl ?? "",
                                        "idNo"                : idNumber,
                                        "realName"            : realname]
        
        user_provider.originRequest(.verification(params), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
                    guard let weakSelf = self else { return }
                    switch result {
                    case .success(let response):
                        if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                            
                            if code == 200{
                                DispatchQueue.main.async {
                                    if let completionHandler = weakSelf.completionHandler {
                                        completionHandler()
                                    }
                                    weakSelf.navigationController?.popViewController(animated: true)
                                }
                            } else {
                                DispatchQueue.main.async {
                                    AlertManager.presentAlertView(message: datas["message"] as! String,duration: 2)
                                }
                            }
                            
                        }
                        break
                    case let .failure(error):
                        AlertManager.presentAlertView(message: error.localizedDescription)
                        break
                    }
                }
    }
    
//    func certificationTableView(_ tableView: CertificationTableView, willSubmitInfosWithPortrait portrait: UIImage, nickname: String, gender: LocalGenderModel.GenderType, birthday: String, location: String) {
//
//        debugPrint("ajdlfjlaksd")
//
////        if let a = alertView {
////            a.dismiss()
////            self.alertView = nil
////        }
//
//        let a = AlertManager.presentAlertView(message: "请稍候", autoPresent: false)
//        a.isBackgroundCoverEnabled = true
//        a.backgroundCoverBackgroundColor = UIColor.black.withAlphaComponent(0.5)
//        a.isBackgroundCoverViewGestureEnabled = false
//        a.shouldAutoDismiss = false
//        a.isDismissButtonHidden = true
////        self.alertView = a
//        a.present()
//
//        /// 添加 indicator
//        _ = self.provider.originRequest(.upload(portrait), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in
//
//            /// 取消 indicator
//            guard let weakSelf = self else { return }
//            switch result {
//            case let .success(response):
//                guard let dict = try? response.mapJSON() as? [String:Any], let code = dict["code"] as? Int else { return }
//                if code == 200, let imageUrl = dict["result"] as? String  {
//                    weakSelf.uploadInitializeUserInfos(portrait: imageUrl, nickname: nickname, gender: gender.requestType, birthday: birthday, location: location)
//                } else {
//                    DispatchQueue.main.async {
//                        a.dismiss()
//                        AlertManager.presentAlertView(message: "上传头像失败")
//                    }
//                }
//                break
//
//            case let .failure(error):
//                DispatchQueue.main.async {
//                    a.dismiss()
//                    AlertManager.presentAlertView(message: error.localizedDescription)
//                }
//                break
//
//            }
//        }
//    }
//
//    private func uploadInitializeUserInfos(portrait: String, nickname: String, gender: Int, birthday: String, location: String) {
//
//        let params: [String: Any] = ["realName"           : portrait,
//                                     "idImgUrlFront"      : location,
//                                     "idImgUrlFront"      : nickname,
//                                     "sex"                : gender]
//
//        user_provider.originRequest(.verification(params), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
//            guard let weakSelf = self else { return }
//            DispatchQueue.main.async {
////                weakSelf.alertView?.dismiss()
//            }
//            switch result {
//            case .success(let response):
//                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
//
//                    if code == 200, let result = datas["result"] as? [String: Any] {
//                        /// 刷新用户模型
//                        UserCenter.default.set(with: result)
//                        DispatchQueue.main.async {
//                            guard let status = UserCenter.default.userStatus, let sex = UserCenter.default.sex else { return }
//                            if sex == 0 {
//
//                                if let name = UserCenter.default.userName, let pwd = UserCenter.default.userPassword {
//                                    IMLoginManager.login(name, pwd, complete: {
//                                        /// 设置用户模型
//                                        UserCenter.default.set(with: result)
//                                        AlertManager.presentAlertView(message: "登录成功", duration: 1) {
//                                            UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
//                                        }
//                                    }) {
//                                        UserCenter.default.clear()
//                                        IMLoginManager.logout()
//                                        AlertManager.presentAlertView(message: "登录失败")
//                                    }
//                                } else {
//                                    UserCenter.default.logout()
//                                }
//
//                            } else {
//                                let c = UIAlertController(title: "视频验证", message: "你将进入视频验证环节，是否进入", preferredStyle: .alert)
//                                let a1 = UIAlertAction(title: "是", style: .default) { (action) in
//                                    UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
//                                }
//                                let a2 = UIAlertAction(title: "否", style: .cancel) { (action) in
//                                    weakSelf.navigationController?.popViewController(animated: true)
//                                }
//                                c.addAction(a1)
//                                c.addAction(a2)
//                                weakSelf.present(c, animated: true, completion: nil)
//
//                            }
//                        }
//                    } else {
//                        AlertManager.presentAlertView(message: "验证失败")
//                    }
//
//                }
//                break
//            case let .failure(error):
//                AlertManager.presentAlertView(message: error.localizedDescription)
//                break
//            }
//        }
//
//
//    }
    
}
